﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace carApp
{
    public partial class weixiudan : Form
    {
        public weixiudan()
        {
            InitializeComponent();
        }
        public weixiudan(int id)
        {
            DataID = id;
            InitializeComponent();
        }
        public weixiudan(string _userId)
        {
            userId = _userId;
            InitializeComponent();
        }
        string userId = "";
        int DataID = 0;
        int dgRow = 0;
        //int dgCol = 0;
        static int pageHeight = 360;//单张375
        static int pageWidth = 810;
        static int totalHeight = 0;
        static DataTable goods_dt = new DataTable();
        static int pageNum = 1;
        static string sn = "";
        private void weixiudan_Load(object sender, EventArgs e)
        {
            txtsn.Text = "QX" + DateTime.Now.ToString("yyyyMMddhhmmss");
            if(DataID>0)
            {
                loadData();
            }
            if (userId.Length>0)
            {
                Model.users m_user = db.FillModel<Model.users>("users","id="+userId);
                if(m_user!=null)
                {
                    txtUser.Text = m_user.xingming;
                    txtUserPhoto.Text = m_user.haoma;
                    txtChepai.Text = m_user.chepai;
                }
            }
        }
        void loadData()
        {
            Model.Ticket ticket = new Model.Ticket();
            ticket = db.FillModel<Model.Ticket>("ticket", "id=" + DataID);
            txtFee.Text = ticket.fee.ToString();
            Model.users user = new Model.users();
            user = db.FillModel<Model.users>("users", "id=" + ticket.userid);
            txtKM.Text = user.km;
            txtUser.Text = user.xingming;
            txtUserPhoto.Text = user.haoma;            
            txtAmount.Text = Math.Round(ticket.amount, 2).ToString();            
            txtMaker.Text = ticket.maker;
            cmbMark.Text = ticket.mark;            
            txtsn.Text = ticket.sn;
            if (ticket.pay_status == 1)
            {
                rdb_pay0.Checked = false;
            }
            else
            {
                rdb_pay1.Checked = true;
            }
           
            DateTime dt = Convert.ToDateTime(ticket.times);
            dtp_times.Value = dt;
            DataTable table= db.JsonToDataTable(ticket.items);
            dataGridView1.DataSource = table;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (txtAppPhoto.TextLength == 0)
            {
                MessageBox.Show("请输入单据号");
                return;
            }
            if (txtUser.Text == "")
            {
                MessageBox.Show("请输入收货单位");
                return;
            }
            saveTicket(true);
        }
        void saveTicket(bool Show)
        {
            DataTable dt = GetDgvToTable();
            Model.Ticket ticket = new Model.Ticket();
            ticket.sn = txtsn.Text;
            ticket.acceper = txtUser.Text;
            ticket.accep_type = "";
            ticket.amount = decimal.Parse(txtAmount.Text);
            ticket.danwei = txtUser.Text;
            ticket.mark = cmbMark.Text;
            ticket.maker = txtMaker.Text;
            ticket.payer = txtUser.Text;
            ticket.fee = decimal.Parse(txtFee.Text);
            int userId = db.getId("users", "xingming='"+txtUser.Text.Replace("'","‘")+ "' and haoma='" + txtUserPhoto.Text + "' and chepai = '"+txtChepai.Text+"'");
            if (userId==0)
            {
                Model.users users = new Model.users();
                users.bumen = "";
                users.chepai = txtChepai.Text;
                users.km = txtKM.Text;
                users.danwei = "";
                users.haoma = txtUserPhoto.Text;
                users.jialing = "0";
                users.jiashizheng = "";
                users.mima = "";
                users.xingming = txtUser.Text;
                users.zhanghao = "";
                users.zhiwu = "";
                userId = db.add(users);
            }
            ticket.userid = userId;
            int payStatus = 1;
            if (rdb_pay0.Checked)
                payStatus = 0;
            ticket.pay_status = payStatus;
            ticket.pay_type = "";
            ticket.print_num = 0;
            ticket.times = dtp_times.Value.ToString("yyyy-MM-dd HH:mm:ss");
            ticket.typeid = 1;
            ticket.items = db.DataTableToJson(dt);
            int res = 0;
            if (db.count("ticket", "sn='" + ticket.sn + "'") == 0)
            {
                res = db.add(ticket);
                if (res > 0)
                {
                    //减去库存
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["sn"].ToString().Length > 0)
                        {
                            try
                            {
                                db.decr("goods", "sn='" + dt.Rows[i]["sn"].ToString() + "'", "stock", int.Parse(dt.Rows[i]["num"].ToString()));
                                db.inc("goods", "sn='" + dt.Rows[i]["sn"].ToString() + "'", "out_stock", int.Parse(dt.Rows[i]["num"].ToString()));
                            }
                            catch //(Exception ex)
                            { }
                        }
                    }
                }
            }
            else
            {
                ticket.id = db.getId("ticket", "sn='" + ticket.sn + "'");
                res = db.edit(ticket);
            }
            if (Show)
            {
                if (res > 0)
                {
                    MessageBox.Show("保存成功");
                }
                else
                {
                    MessageBox.Show("保存失败");
                }
            }
        }
        private DataTable GetDgvToTable()
        {
            DataTable dt = new DataTable();
            if (dataGridView1.Rows.Count > 0)
            {
                dt.Columns.Add("id");
                dt.Columns.Add("sn");
                dt.Columns.Add("name");               
                dt.Columns.Add("num");
                dt.Columns.Add("price");
                dt.Columns.Add("totalprice");
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (!dataGridView1.Rows[i].IsNewRow)
                    {
                        DataRow dr = dt.NewRow();
                        var id = "0";
                        if (dataGridView1.Rows[i].Cells[0].Value != null)
                        {
                            id = dataGridView1.Rows[i].Cells[0].Value.ToString();
                        }
                        dr[0] = id;
                        dr["sn"] = dataGridView1.Rows[i].Cells[1].Value.ToString();
                        dr["name"] = dataGridView1.Rows[i].Cells[2].Value.ToString();
                        dr["num"] = dataGridView1.Rows[i].Cells[3].Value.ToString();
                        dr["price"] = dataGridView1.Rows[i].Cells[4].Value.ToString();
                        dr["totalprice"] = dataGridView1.Rows[i].Cells[5].Value.ToString();
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GoodsSelect goods = new GoodsSelect(2);
            goods.Owner = this;
            goods.ShowDialog();
        }
        public void addGoodsToDataView(string goodsId,int priceType)
        {
            if (goodsId.Length > 0)
            {
                decimal total = 0;
                try
                {
                    DataTable dt = db.GetTable("goods", "id in(" + goodsId + ")");
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        var id = dt.Rows[i]["id"].ToString();
                        var sn = dt.Rows[i]["sn"].ToString();
                        var name = dt.Rows[i]["name"].ToString();
                        var price = dt.Rows[i]["price"].ToString();
                        if(priceType==2)
                        {
                            price = dt.Rows[i]["price1"].ToString();
                        }
                        else if(priceType==3)
                        {
                            price = dt.Rows[i]["price2"].ToString();
                        }
                        var totalPrice = price;
                        total += decimal.Parse(totalPrice);
                        dataGridView1.Rows.Add(new object[] { id, sn, name, "1", price, totalPrice });
                    }
                    total += decimal.Parse(txtFee.Text);
                    txtAmount.Text = Math.Round(total, 2).ToString();
                }
                catch
                { }
                
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dgRow = e.RowIndex;
            if (e.ColumnIndex == 1)
            {
                try
                {
                    var sn = dataGridView1.Rows[dgRow].Cells[1].Value.ToString();
                    Console.WriteLine(sn);
                    if (sn.Length > 0)
                    {
                        DataTable dt = db.GetTable("goods", "sn='" + sn + "'");
                        if (dt.Rows.Count > 0)
                        {
                            dataGridView1.Rows[dgRow].Cells[2].Value = dt.Rows[0]["name"].ToString();
                            dataGridView1.Rows[dgRow].Cells[3].Value = "1";
                            dataGridView1.Rows[dgRow].Cells[4].Value = dt.Rows[0]["price"].ToString();
                            dataGridView1.Rows[dgRow].Cells[5].Value = dt.Rows[0]["price"].ToString();
                        }
                        getTotalPrice();
                    }
                }
                catch// (Exception ex)
                { }
            }
            else if (e.ColumnIndex == 3)
            {
                try
                {
                    string num = dataGridView1.Rows[dgRow].Cells[3].Value.ToString();
                    if (num.Length > 0 && Libs.Utils.isNumber(num, true))
                    {
                        if (dataGridView1.Rows[dgRow].Cells[4].Value != null)
                        {
                            if (dataGridView1.Rows[dgRow].Cells[4].Value.ToString().Length > 0)
                            {
                                decimal newPrice = decimal.Parse(dataGridView1.Rows[dgRow].Cells[3].Value.ToString()) * decimal.Parse(dataGridView1.Rows[dgRow].Cells[4].Value.ToString());
                                dataGridView1.Rows[dgRow].Cells[5].Value = Math.Round(newPrice, 2);
                            }
                        }
                    }
                    else
                    {
                        if (dataGridView1.Rows[dgRow].Cells[4].Value != null)
                        {
                            dataGridView1.Rows[dgRow].Cells[3].Value = "1";
                            dataGridView1.Rows[dgRow].Cells[5].Value = dataGridView1.Rows[dgRow].Cells[4].Value;
                        }
                    }
                    getTotalPrice();
                }
                catch
                { }
            }
            else if (e.ColumnIndex == 4)
            {
                try
                {
                    if (dataGridView1.Rows[dgRow].Cells[4].Value != null && dataGridView1.Rows[dgRow].Cells[3].Value != null)
                    {
                        if (dataGridView1.Rows[dgRow].Cells[4].Value.ToString().Length > 0)
                        {
                            string price = dataGridView1.Rows[dgRow].Cells[4].Value.ToString();
                            if (price.Length > 0 && Libs.Utils.isNumber(price, true))
                            {
                                decimal newPrice = decimal.Parse(dataGridView1.Rows[dgRow].Cells[3].Value.ToString()) * decimal.Parse(price);
                                dataGridView1.Rows[dgRow].Cells[5].Value = Math.Round(newPrice, 2);
                            }
                        }
                    }
                    getTotalPrice();
                }
                catch
                { }
            }
            
        }
        int CurrentRowIndex = 0;
        int CurrentColumnIndex = 0;

        private void button5_Click(object sender, EventArgs e)
        {
            if (txtsn.TextLength == 0)
            {
                MessageBox.Show("请输入单据号");
                return;
            }
            if (txtUser.Text == "")
            {
                MessageBox.Show("请输入客户姓名");
                return;
            }
            if (txtUserPhoto.Text == "")
            {
                MessageBox.Show("请输入客户号码");
                return;
            }
            saveTicket(false);
            sn = txtsn.Text;
            goods_dt = GetDgvToTable();
            print(true);
        }
        private static void print(bool doit)
        {
            Model.Prints prints = new Model.Prints();
            prints.name = Libs.Utils.getDefaultPrints();
            prints.page_height = pageHeight;
            prints.page_width = pageWidth;
            prints.page_left = 0;
            prints.page_top = 0;
            DataTable dt_print = db.GetTable("prints", "status=1");
            if (dt_print.Rows.Count > 0)
            {
                //prints.name = dt_print.Rows[0]["name"].ToString();
                prints.page_height = int.Parse(dt_print.Rows[0]["page_height"].ToString());
                prints.page_width = int.Parse(dt_print.Rows[0]["page_width"].ToString());
                prints.page_left = int.Parse(dt_print.Rows[0]["page_left"].ToString());
                prints.page_top = int.Parse(dt_print.Rows[0]["page_top"].ToString());
            }
            System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
            System.Drawing.Printing.Margins margin = new System.Drawing.Printing.Margins(prints.page_left, 0, prints.page_top, 0);
            pd.DefaultPageSettings.Margins = margin;
            totalHeight = prints.page_height * pageNum;
            System.Drawing.Printing.PaperSize pageSize = new System.Drawing.Printing.PaperSize("print_ticket", prints.page_width, totalHeight);
            pd.DefaultPageSettings.PaperSize = pageSize;
            pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd_PrintPage);
            pd.PrinterSettings.PrinterName = prints.name;//指定打印机
            PrintPreviewDialog ppd = new PrintPreviewDialog();
            ppd.Document = pd;
            ppd.ShowDialog();

            return;
            try
            {
                if (!doit)
                {
                    //PrintPreviewDialog ppd = new PrintPreviewDialog();
                    //ppd.Document = pd;
                    //ppd.ShowDialog();
                }
                else
                {
                    pd.Print();

                }
            }
            catch// (Exception ex)
            {
                pd.PrintController.OnEndPrint(pd, new System.Drawing.Printing.PrintEventArgs());
            }
        }
        private static void pd_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                //string pr_string = "";
                
                Graphics g = e.Graphics;
                Pen pen_line = new Pen(Color.Gray,1);
                Font ft = new Font("宋体", 8F, FontStyle.Regular);
                Font ft_head = new Font("宋体", 8F, FontStyle.Bold);
                #region drawing
                Model.Ticket ticket = db.FillModel<Model.Ticket>("ticket", "sn='" + sn + "'");
                Model.users user = db.FillModel<Model.users>("users", "id=" + ticket.userid + "");
                db.inc("ticket", "sn='" + sn + "'", "print_num");
                DateTime dt = Convert.ToDateTime(ticket.times);
                var appData_danwei = db.ExecuteScalar("appconfig", "val", "id=1");
                var appData_haoma = db.ExecuteScalar("appconfig", "val", "id=2");
                //g.DrawString("|--", new Font("宋体", 2F, FontStyle.Regular), new SolidBrush(Color.Black), new Point(1, 1));
                g.DrawString("广西吉力士贸易有限公司", new Font("宋体", 16F, FontStyle.Regular), new SolidBrush(Color.Black), new Point(pageWidth / 2 - 125, 0));
                g.DrawString("汽车维修保养单", new Font("宋体", 13F, FontStyle.Regular), new SolidBrush(Color.Black), new Point(pageWidth/2 - 65, 30));
                g.DrawString("地址：" + appData_danwei, ft, new SolidBrush(Color.Black), new Point(30, 70));
                g.DrawString("维修电话：" + appData_haoma, ft, new SolidBrush(Color.Black), new Point(650, 70));
                
                g.DrawLine(pen_line, 30, 85, 780, 85);
                //客户信息
                int head_y = 92;
                int lineY1 = 85;
                int lineY2 = 110;
                g.DrawLine(pen_line, 30, lineY1, 30, lineY2);
                g.DrawString("客户", ft, new SolidBrush(Color.Black), new Point(37, head_y));
                g.DrawLine(pen_line, 70, lineY1, 70, lineY2);
                g.DrawString(ticket.payer, ft, new SolidBrush(Color.Black), new Point(75, head_y));
                g.DrawLine(pen_line, 180, lineY1, 180, lineY2);

                g.DrawString("车牌号", ft, new SolidBrush(Color.Black), new Point(187, head_y));
                g.DrawLine(pen_line, 230, lineY1, 230, lineY2);
                g.DrawString(user.chepai, ft, new SolidBrush(Color.Black), new Point(235, head_y));               
                g.DrawLine(pen_line, 320, lineY1, 320, lineY2);

                g.DrawString("公里数", ft, new SolidBrush(Color.Black), new Point(327, head_y));                
                g.DrawLine(pen_line, 370, lineY1, 370, lineY2);
                g.DrawString(user.km+"KM", ft, new SolidBrush(Color.Black), new Point(375, head_y));
                g.DrawLine(pen_line, 435, lineY1, 435, lineY2);

                g.DrawString("客户电话" , ft, new SolidBrush(Color.Black), new Point(443, head_y));
                g.DrawLine(pen_line, 495, lineY1, 495, lineY2);
                g.DrawString(user.haoma, ft, new SolidBrush(Color.Black), new Point(500, head_y));
                g.DrawLine(pen_line, 625, lineY1, 625, lineY2);

                g.DrawString("日期", ft, new SolidBrush(Color.Black), new Point(630, head_y));
                g.DrawLine(pen_line, 665, lineY1, 665, lineY2);
                g.DrawString(dt.Year.ToString() + " 年", ft, new SolidBrush(Color.Black), new Point(670, head_y));
                g.DrawString(dt.Month.ToString() + " 月", ft, new SolidBrush(Color.Black), new Point(720, head_y));
                g.DrawString(dt.Day.ToString() + " 日", ft, new SolidBrush(Color.Black), new Point(750, head_y));
                g.DrawLine(pen_line, 780, lineY1, 780, lineY2);
                g.DrawLine(pen_line, 30, 110, 780, 110);
                
                #region 绘制表头
                head_y = 115;
                lineY1 = 110;
                lineY2 = 130;
                g.DrawLine(pen_line, 30, lineY1, 30, lineY2);
                g.DrawString("序号", ft_head, new SolidBrush(Color.Black), new Point(35, head_y));
                g.DrawLine(pen_line, 70, lineY1, 70, lineY2);
                g.DrawString("项目", ft_head, new SolidBrush(Color.Black), new Point(75, head_y));
                g.DrawLine(pen_line, 320, lineY1, 320, lineY2);
                g.DrawString("单价（元）", ft_head, new SolidBrush(Color.Black), new Point(340, head_y));
                g.DrawLine(pen_line, 420, lineY1, 420, lineY2);
                g.DrawString("数量", ft_head, new SolidBrush(Color.Black), new Point(450, head_y));
                g.DrawLine(pen_line, 510, lineY1, 510, lineY2);
                g.DrawString("金额（元）", ft_head, new SolidBrush(Color.Black), new Point(525, head_y));
                g.DrawLine(pen_line, 600, lineY1, 600, lineY2);
                g.DrawString("备注", ft_head, new SolidBrush(Color.Black), new Point(640, head_y));
                g.DrawLine(pen_line, 780, lineY1, 780, lineY2);
                #endregion
                g.DrawLine(pen_line, 30, 130, 780, 130);               
                #region 输出产品信息
                head_y = 130;
                int goods_begin = head_y;
                int line_height = 15;
                decimal total_num = 0;
                decimal total_price = 0;
                lineY1 = 130;
                lineY2 = 150;
                int index = 0;
                for (int i = 0; i < goods_dt.Rows.Count; i++)
                {
                    if (goods_dt.Rows[i][2].ToString().Length == 0)
                        continue;                    
                    if(i==0)
                    {
                        head_y += 10;
                    }
                    else
                    {
                        head_y = (i) * line_height + goods_begin+10;
                    }
                    index = i + 1;
                    total_num += decimal.Parse(goods_dt.Rows[i][3].ToString());
                    total_price += decimal.Parse(goods_dt.Rows[i][5].ToString());                    
                    g.DrawString(index.ToString(), ft, new SolidBrush(Color.Black), new Point(40, head_y));
                    g.DrawString(goods_dt.Rows[i][2].ToString(), ft, new SolidBrush(Color.Black), new Point(75, head_y));
                    g.DrawString(goods_dt.Rows[i][4].ToString(), ft, new SolidBrush(Color.Black), new Point(340, head_y));
                    g.DrawString(goods_dt.Rows[i][3].ToString(), ft, new SolidBrush(Color.Black), new Point(450, head_y));
                    g.DrawString(goods_dt.Rows[i][5].ToString(), ft, new SolidBrush(Color.Black), new Point(510, head_y));                   
                }
                //如果有工时费
                index++;
                head_y += 20;
                var fee = ticket.fee.ToString();
                g.DrawString(index.ToString(), ft, new SolidBrush(Color.Black), new Point(40, head_y));
                g.DrawString("工时费", ft, new SolidBrush(Color.Black), new Point(75, head_y));
                g.DrawString(fee, ft, new SolidBrush(Color.Black), new Point(340, head_y));
                g.DrawString("1", ft, new SolidBrush(Color.Black), new Point(450, head_y));
                g.DrawString(fee, ft, new SolidBrush(Color.Black), new Point(510, head_y));
                total_price += ticket.fee;
                g.DrawString("合计：", ft, new SolidBrush(Color.Black), new Point(350, head_y + 25));
                g.DrawString(total_num.ToString(), ft, new SolidBrush(Color.Black), new Point(450, head_y + 25));
                g.DrawString(total_price.ToString("0.00"), ft, new SolidBrush(Color.Black), new Point(510, head_y + 25));
                #endregion
                head_y += 55;
                g.DrawLine(pen_line, 30, lineY1, 30, head_y);
                g.DrawLine(pen_line, 780, lineY1, 780, head_y);
                g.DrawLine(pen_line, 30, head_y, 780, head_y);
                head_y += 10;

                //g.DrawString("主管：", ft, new SolidBrush(Color.Black), new Point(30, head_y + 85));
                g.DrawString("维修师傅：", ft, new SolidBrush(Color.Black), new Point(100, head_y));
                g.DrawString("制单：", ft, new SolidBrush(Color.Black), new Point(300, head_y));
                g.DrawString("作账：", ft, new SolidBrush(Color.Black), new Point(500, head_y));
                //g.DrawString("|--", new Font("宋体", 2F, FontStyle.Regular), new SolidBrush(Color.Black), new Point(1, totalHeight - 3));
                
                g.Dispose();
                #endregion
                //pr_string = "";
            }
            catch (Exception ex)
            {
                ReportEx.upPortEX(ex.ToString());
            }
        }
        private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            var dgv = (DataGridView)sender;
            CurrentRowIndex = e.RowIndex;
            CurrentColumnIndex = e.ColumnIndex;
        }

        private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && CurrentRowIndex > -1)
            {
                CurrentRowIndex = e.RowIndex;
                this.dataGridView1.Rows[e.RowIndex].Selected = true;
                this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[1];
                contextMenuStrip1.Show(Cursor.Position);
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = dataGridView1.Rows[CurrentRowIndex].Cells[0].Value;           
            this.dataGridView1.Rows.RemoveAt(CurrentRowIndex);
            getTotalPrice();
        }
        void getTotalPrice()
        {
            try
            {
                decimal total = 0;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if(dataGridView1.Rows[i].Cells[5].Value!=null)
                        total += decimal.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString());
                }
                total += decimal.Parse(txtFee.Text);
                txtAmount.Text = Math.Round(total, 2).ToString();
            }
            catch
            { }
        }
        private void label11_Click(object sender, EventArgs e)
        {

        }

        private void txtFee_TextChanged(object sender, EventArgs e)
        {
            if(txtFee.Text.Length>0)
            {
                getTotalPrice();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            PrintSet frm = new PrintSet();
            frm.Show();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            kehuselect frm = new kehuselect();
            frm.Owner = this;
            frm.ShowDialog();
        }
        public void setUserinfo(string[] user)
        {
            if (user.Length > 0)
            {
                txtUser.Text = user[1];
                txtUserPhoto.Text = user[2];
                txtChepai.Text = user[3];
                userId = user[0];
            }
        }
    }
}
